// 请求监控工具
class RequestMonitor {
  private configRequests: Array<{ timestamp: number, stack: string, url?: string }> = [];
  private apiUrlFixes: Array<{ timestamp: number, from: string, to: string }> = [];
  
  logConfigRequest(url?: string) {
    const timestamp = Date.now();
    const stack = new Error().stack || 'No stack trace available';
    
    this.configRequests.push({ timestamp, stack, url });
    
    console.group('🔍 System Config 请求监控');
    console.log('时间:', new Date(timestamp).toISOString());
    console.log('请求URL:', url || '未知');
    console.log('请求堆栈:', stack);
    console.log('总请求次数:', this.configRequests.length);
    
    // 显示最近的请求间隔
    if (this.configRequests.length > 1) {
      const lastTwo = this.configRequests.slice(-2);
      const interval = lastTwo[1].timestamp - lastTwo[0].timestamp;
      console.log('距离上次请求间隔:', interval + 'ms');
      
      if (interval < 5000) {
        console.warn('⚠️  请求间隔过短！');
      }
    }
    
    console.groupEnd();
  }
  
  logApiUrlFix(from: string, to: string) {
    const timestamp = Date.now();
    this.apiUrlFixes.push({ timestamp, from, to });
    
    console.group('🔧 API地址修复');
    console.log('时间:', new Date(timestamp).toISOString());
    console.log('错误地址:', from);
    console.log('修复为:', to);
    console.log('总修复次数:', this.apiUrlFixes.length);
    console.groupEnd();
  }
  
  getRequestHistory() {
    return this.configRequests;
  }
  
  getApiFixHistory() {
    return this.apiUrlFixes;
  }
  
  clearHistory() {
    this.configRequests = [];
    this.apiUrlFixes = [];
    console.log('📋 监控历史已清除');
  }
  
  // 检查当前API配置状态
  checkApiStatus() {
    console.group('📊 API状态检查');
    console.log('配置请求总数:', this.configRequests.length);
    console.log('地址修复总数:', this.apiUrlFixes.length);
    
    if (this.apiUrlFixes.length > 0) {
      console.warn('⚠️  检测到API地址错误，已自动修复');
      console.table(this.apiUrlFixes.slice(-5)); // 显示最近5次修复
    } else {
      console.log('✅ API地址配置正常');
    }
    
    if (this.configRequests.length > 0) {
      const lastRequest = this.configRequests[this.configRequests.length - 1];
      console.log('最后一次请求:', new Date(lastRequest.timestamp).toISOString());
      console.log('最后请求URL:', lastRequest.url);
    }
    
    console.groupEnd();
  }
}

export const requestMonitor = new RequestMonitor();

// 在全局暴露监控器，方便调试
if (typeof window !== 'undefined') {
  (window as any).requestMonitor = requestMonitor;
  
  // 添加快捷调试命令
  (window as any).checkApiStatus = () => requestMonitor.checkApiStatus();
  (window as any).clearApiHistory = () => requestMonitor.clearHistory();
} 